<template>
  <div class="page-container">
    <el-form :inline="true" @submit.prevent="fetchTasks">
      <el-form-item label="用户ID">
        <el-input v-model="assignee" placeholder="请输入用户ID" style="width: 200px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchTasks">查询任务</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tasks" border stripe style="width: 100%" v-loading="loading">
      <el-table-column align="center" prop="id" label="任务ID" width="280"></el-table-column>
      <el-table-column align="center" prop="name" label="任务名称"></el-table-column>
      <el-table-column align="center" prop="assignee" label="处理人"></el-table-column>
      <el-table-column align="center" label="创建时间" width="160">
        <template #default="{ row }">
          {{ new Date(row.createTime).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="所属流程实例" width="280">
        <template #default="{ row }">
          {{ row.processInstanceId }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="120">
        <template #default="{ row }">
          <el-button size="small" type="success" @click="completeTask(row.id)">
            完成
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import axios from 'axios'
import {ElMessage} from "element-plus";

const tasks = ref([])
const assignee = ref('user1') // 默认测试用户
const loading = ref(false)

// 获取用户任务
const fetchTasks = async () => {
  if (!assignee.value.trim()) {
    ElMessage.warning('请填写用户ID')
    return
  }

  loading.value = true
  try {
    const res = await axios.get('/api/workflow/tasks', {
      params: { assignee: assignee.value }
    })
    tasks.value = res.data || []
  } catch (err) {
    console.error('获取任务失败:', err)
    ElMessage.error('获取任务失败')
  } finally {
    loading.value = false
  }
}

// 完成任务
const completeTask = async (taskId) => {
  try {
    await axios.post(`/api/workflow/task/${taskId}/complete`)
    ElMessage.success('任务完成成功')
    await fetchTasks() // 刷新任务列表
  } catch (err) {
    console.error('完成任务失败:', err)
    ElMessage.error('任务完成失败: ' + (err.response?.data || err.message))
  }
}

onMounted(() => {
  fetchTasks();
});
</script>

<style scoped>
.page-container {
  padding: 20px;
}
</style>
